package com.lishe.lishe.lishe.module.me.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.TipDialog;
import com.lishe.lishe.lishe.module.me.bean.PhotoItem;
import com.lishe.lishe.lishe.module.me.crop.Crop;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.me.others.ImageSelector;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ValidationUtils;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhcasecom on 2017/8/18.
 * 意见反馈
 */

public class AdviceActivity extends BaseActivity implements View.OnClickListener {
    private String TAG = getClass().getSimpleName();
    private TextView titletxt;
    private EditText linkName, linkNumber, content;
    private Button sendBtn;
    private ImageView addPicture;
    private String linkmanStr, numberStr, contentStr;
    private HorizontalScrollView Image_container;

    private TipDialog.Builder builder;
    private TipDialog mDialog;

    private LinearLayout image_container_layout;

    private HashMap paramsFile = new HashMap();

    HashMap<String, File> mapImage = new HashMap<>();

    private HashMap params = new HashMap();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advice);
        initView();
    }

    private void initView() {
        titletxt = findViewById(R.id.title_text_title);
        titletxt.setText(R.string.suggest_title);
        linkName = findViewById(R.id.linkName);
        linkNumber = findViewById(R.id.linkNumber);
        content = findViewById(R.id.suggest_content);
        sendBtn = findViewById(R.id.sendSuggest);
        sendBtn.setOnClickListener(this);
        addPicture = findViewById(R.id.add_picture3);
        addPicture.setOnClickListener(this);
        Image_container = findViewById(R.id.Image_container);
        Image_container.setHorizontalScrollBarEnabled(true);
        builder = new TipDialog.Builder(this);
        image_container_layout = findViewById(R.id.image_container_layout);
        Button back = findViewById(R.id.title_left_button);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


    }

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, AdviceActivity.class);
        activity.startActivity(intent);
    }


    /**
     * 判断手机格式是否正确
     *
     * @param str 需要判断的字符串
     * @return 返回true说明字符串匹配成功
     */
    // Pattern类的作用在于编译正则表达式后创建一个匹配模式. Matcher类使用Pattern实例提供的模式信息对正则表达式进行匹配
    private boolean isPhone(String str) {
        // 将给定的正则表达式编译并赋予给Pattern类
        Pattern pattern = Pattern.compile("1[0-9]{10}");
        // 对指定输入的字符串创建一个Matcher对象
        Matcher matcher = pattern.matcher(str);
        // 尝试对整个目标字符展开匹配检测,也就是只有整个目标字符串完全匹配时才返回真值.
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sendSuggest:

                sendSuggestData();
                break;
            case R.id.add_picture3:
                if (mapImage.size() > 3 || mapImage.size() == 3) {
                    Toast.makeText(this, "最多上传三张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
//                Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
//                /**
//                 * 下面这句话，与其它方式写是一样的效果，如果：
//                 * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                 * intent.setType(""image/*");设置数据类型
//                 * 要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
//                 */
//                albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                startActivityForResult(albumIntent, 1);
                Crop builder = Crop.of(Uri.parse("image:input"), Uri.parse("image:output"));
                builder.withMaxSize(400, 400);
                builder.withAspect(1, 1);
                Crop.pickImage(this);
                break;

        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, final Intent result) {
//        switch (requestCode) {
//            case 1:
//                //从相册中获取到图片了，才执行裁剪动作
//                if (result != null) {
//                    Log.e(TAG, "uri" + result.getData().toString());
//                    clipPhoto(result.getData());
//                }
//                break;
//            case 3:
//                /**
//                 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，
//                 * 要重新裁剪，丢弃 当前功能时，会报NullException
//                 */
//                if (result != null) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            setPicToView(result);
//                        }
//                    });
//
//                }
//                break;
//        }
//
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
            beginCrop(result.getData());
        } else if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, result);
        }
    }

    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().start(this);
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            setPicToView(result);
        } else if (resultCode == Crop.RESULT_ERROR) {
            Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


    private void moveItem(PhotoItem item) {
        mapImage.remove(item.Id);
//        getParams();
    }

    private void getParams() {
        paramsFile.clear();
        int i= 1;
        Iterator iter = mapImage.entrySet().iterator();
        while (iter.hasNext()) {
            String key = String.format("images%d", i);
            Map.Entry entry = (Map.Entry) iter.next();
            Object val = entry.getValue();
            paramsFile.put(key,val);
            Log.e(TAG,"paramsFile-------->"+paramsFile.toString());
            i++;
        }

    }

    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            PhotoItem item = new PhotoItem();
            Uri uri = picdata.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
            item.uri = uri;
            item.Id = getRandomString(12);
            ImageSelector selector = new ImageSelector(this, item, new ImageSelector.OnClickListner() {
                @Override
                public void onclick(PhotoItem item) {
                    moveItem(item);
                    Log.e(TAG, "图片有" + mapImage.size());
                }
            });

            if (selector != null) {
                selector.setImageResource();
                image_container_layout.addView(selector);
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) selector.getLayoutParams();
                lp.weight = LinearLayout.LayoutParams.WRAP_CONTENT;
                lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                lp.rightMargin = 10;
                selector.setLayoutParams(lp);
                image_container_layout.invalidate();
            }
            Bitmap bmp = null;
            try {
                bmp = getBitmap(uri);
                Log.e(TAG, "获取的图片" + bmp);
            } catch (IOException e) {
                e.printStackTrace();
            }
            saveBitmapFile(bmp, item);
        }
    }

    /**
     * 生成随机字符串当作Id
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    private final Bitmap getBitmap(Uri url)
            throws FileNotFoundException, IOException {
        ContentResolver cr = AdviceActivity.this.getContentResolver();
        InputStream input = cr.openInputStream(url);
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        input.close();
        return bitmap;
    }

    public void saveBitmapFile(Bitmap bitmap, PhotoItem item) {
        String key = String.format("images%d", mapImage.size() + 1);
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lishe/pics/");//将要保存图片的路径
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lishe/pics/" + key + ".png");//将要保存图片的路径
        Log.e(TAG, "本地绝对路径" + Environment.getExternalStorageDirectory().getAbsolutePath().toString());
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mapImage.put(item.Id, file);
        Log.e(TAG, "图片有" + mapImage.size());
    }

    private void sendSuggestData() {
        linkmanStr = linkName.getText().toString();
        numberStr = linkNumber.getText().toString();
        contentStr = content.getText().toString();
        if (linkmanStr.length() > 0) {
            if (numberStr.length() > 0) {
                if (ValidationUtils.isMobileNO(numberStr)) {
                    if (contentStr.length() > 15) {
                        postSuggestData();
                    } else {
                        toast("请输入大于15个字符的意见或建议");
                    }

                } else {
                    toast("请输入正确的手机号码");
                }
            } else {
                toast("联系电话不能为空，请输入");
            }

        } else {
            toast("联系人不能为空，请输入");
        }


    }

    private void postSuggestData() {

        params.put("linkman", linkmanStr);
        params.put("mobile", numberStr);
        params.put("content", contentStr);
        //将listImage中的uri转换为file文件
        getParams();
//        if (paramsFile.size() > 0) {
//            params.putAll(paramsFile);
//            Log.e(TAG, params.toString());
//        }
        Log.e(TAG, "params的大小为" + params.size());
        try {
            LoadingUtils.createLoadingDialog(this, null, true);
            HttpUserCenter.postSuggestData(this,params,paramsFile, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    LSWebHelper.WebUpLoadFileCallBack response = new LSWebHelper.WebUpLoadFileCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            //             toast("您的意见我们已经收到，并会尽快处理");
            LoadingUtils.closeDialog();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showtipWindow("意见反馈", "亲您的意见我们已经收到，我们会尽快处理", "确定", "取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            finish();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                        }
                    });

                }
            });
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lishe/pics/");
           delAllfile(f);
        }

        @Override
        public void onFailure(String message) {

            LoadingUtils.closeDialog();
            Toast.makeText(AdviceActivity.this, message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProgress(int count) {
            Log.e(TAG, "Image count:" + count);

        }

    };

    /**
     * 删除指定目录下面所有文件
     *
     * @param f
     */
    private void delAllfile(File f) {
        if (f == null) {
            return;
        } else if (f.exists()) {//如果此抽象指定的对象存在并且不为空。
            if (f.isFile()) {
                f.delete();//如果此抽象路径代表的是文件，直接删除。
            } else if (f.isDirectory()) {//如果此抽象路径指代的是目录
                String[] str = f.list();//得到目录下的所有路径
                if (str == null) {
                    f.delete();//如果这个目录下面是空，则直接删除
                } else {//如果目录不为空，则遍历名字，得到此抽象路径的字符串形式。
                    for (String st : str) {
                        delAllfile(new File(f, st));
                    }//遍历清楚所有当前文件夹里面的所有文件。
                    f.delete();//清楚文件夹里面的东西后再来清楚这个空文件夹
                }
            }
        }
    }

    private void showtipWindow(String title, String content, String confirmText, String cancelText, View.OnClickListener conFirmListener, View.OnClickListener cancelListener) {
        mDialog = builder.setMessage(title, content)
                .setPositiveButton(confirmText, conFirmListener)
                .setNegativeButton(cancelText, cancelListener)
                .createTwoButtonDialog();
        mDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/lishe/pics/");
        delAllfile(f);
    }
}
